package org.jinyan.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class VOMapUtils {

	public static Map voToMap(Object vo) {
		Map voMap = new HashMap();
		Field[] fs = vo.getClass().getDeclaredFields();
		for (int i = 0; i < fs.length; i++) {
			Field f = fs[i];
			String varName = f.getName();
			boolean tempAccess = f.isAccessible();
			f.setAccessible(true);
			try {
				Object obj = f.get(vo);
				if (obj != null || !"".equals(obj)) {
					voMap.put(varName, obj);
				}
				f.setAccessible(tempAccess);
			} catch (IllegalArgumentException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return voMap;
	}

	private static void setMethod(Object method, Object value, Object thisObj) {

		try {
			Class c = Class.forName(thisObj.getClass().getName());
			String met = (String) method;
			met = met.trim();
			if (!met.substring(0, 1).equals(met.substring(0, 1).toUpperCase())) {
				met = met.substring(0, 1).toUpperCase() + met.substring(1);
			}
			if (!String.valueOf(method).startsWith("set")) {
				met = "set" + met;
			}
			Method m = c.getMethod(met);
			m.invoke(thisObj, value);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

	public static Object mapToVO(Object vo, Map data) {

		Field[] fs = vo.getClass().getDeclaredFields();
		Set set = data.keySet();
		Iterator iterator = set.iterator();
		while (iterator.hasNext()) {
			Object key = iterator.next();
			Object val = data.get(key);
			setMethod(key, val, vo);
		}
		return vo;
	}

}
